<?php
// +----------------------------------------------------------------------
// | 云南喵云科技
// +----------------------------------------------------------------------
// | 官方网站: https://www.meoyun.com
// +----------------------------------------------------------------------
// | Author: 喵大大
// +----------------------------------------------------------------------
// | Email: mmteen@sina.com
// +----------------------------------------------------------------------
// | Date: 2021/10/28/028
// +----------------------------------------------------------------------
// | Time: 17:35
// +----------------------------------------------------------------------
namespace App\HttpController\Api;

use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Jwt\Jwt;

class Base extends Controller
{

    protected $jwtKey = "WVZFUkdLSEpJT1hXRUZOSkgyNDU2QDE/IQ=="; //jwt加密key

    function onException(\Throwable $throwable): void
    {
        $this->message(400, $throwable->getMessage());
    }

    protected function actionNotFound(?string $action)
    {
        $this->message(404,'action not found');
    }


    /**
     * @param $statusCode
     * @param null $msg
     * @param null $data
     */
    public function message($statusCode, $msg = null, $data = null){
        $data = Array(
            "code" => $statusCode,
            "result" => $data,
            "msg" => $msg
        );

        $this->response()->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
        $this->response()->withHeader('Content-type', 'application/json;charset=utf-8');
        $this->response()->withStatus(200);

        $this->response()->end();
    }

    /**
     *   生成token
     * @param $data
     * @return String|null
     */
    public function buildToken($data,$user = 'user'): ?String
    {
        $jwtObject = Jwt::getInstance()
            ->setSecretKey($this->jwtKey) // 秘钥
            ->publish();

        $jwtObject->setAlg('HMACSHA256'); // 加密方式
        $jwtObject->setAud($user); // 用户
        $jwtObject->setExp(time()+3600*24*7); // 过期时间
        $jwtObject->setIat(time()); // 发布时间
        $jwtObject->setIss('easyswoole'); // 发行人
        $jwtObject->setJti(md5(time())); // jwt id 用于标识该jwt
        $jwtObject->setNbf(time()); // 在此之前不可用
        $jwtObject->setSub('主题'); // 主题

        // 自定义数据
        $jwtObject->setData($data);

        // 最终生成的token
        $token = $jwtObject->__toString();

        return $token;
    }

    /**
     *  获得 raw 内容
     * @return mixed
     */
    public function getRaw()
    {
        $params = $this->request()->getBody()->__toString();
        $raw_array = json_decode($params, true);

        return $raw_array;
    }

    /**
     * 获取uid
     * @return mixed|void
     * @throws \EasySwoole\Jwt\Exception
     */
    public function getUid(){
        $header = $this->request()->getHeaders();

        $token = $header["token"][0];

        $jwtObject = Jwt::getInstance()->setSecretKey($this->jwtKey)->decode($token);
        $status = $jwtObject->getStatus();

        switch ($status){

            case 1:
                $data = $jwtObject->getData();
                return $data["uid"];

            case  -1:
                $this->message(420,"token已失效");

            case  -2:
                $this->message(420,"token已过期");
        }
    }

    /**
     * 获取用户通过 POST 或者 GET 提交的参数
     * @param string $name
     * @return array|mixed|object|null
     */
    public function getParam($name = '')
    {
        return $this->request()->getRequestParam($name);
    }

    /**
     * 获取分页数据
     * @param $model
     * @param int $limit
     * @return array
     */
    public function paginate($model, int $limit=10)
    {
        $page = $this->getParam("page");
        $model->limit($limit * ($page - 1), $limit)->withTotalCount();

        // 列表数据
        $list = $model->all();

        $result = $model->lastQueryResult();

        // 总条数
        $total = $result->getTotalCount();

        $pageTotal = $total/$limit;

        $has_more = false;
        if($page < $pageTotal){
            $has_more = true;
        }

        $data = [
            "has_more" => $has_more,
            "total" => $total,
            "per_page" => $limit,
            "current_page" => intval($page),
            "last_page" => $pageTotal,
            "data" => $list
        ];

        return $data;
    }
}